package 基础篇.线程通信.同步锁通信;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author IBM CHEN ZHI KAN
 * @create 2018/7/28
 */
public class Account {
  private String accountNo;//账户编号
  private double balance;//账户余额
  private  final Lock lock=new ReentrantLock();
  //获得锁的condition
  private final Condition cond=lock.newCondition();
  public Account(String accountNo, double balance) {
    this.accountNo = accountNo;
    this.balance = balance;
  }

  public String getAccountNo() {
    return accountNo;
  }

  public void setAccountNo(String accountNo) {
    this.accountNo = accountNo;
  }

  public double getBalance() {
    return balance;
  }

  public void setBalance(double balance) {
    this.balance = balance;
  }
  //取钱
  public  void draw(double drawAmount){
   lock.lock();
   try{
      //如果当前旗标为true，则说明账户有钱，不需要阻塞，开始取钱
      if(balance-drawAmount<0){
        //让当前方法阻塞
        cond.await();
      }else {
     //执行取钱操作
     balance-=drawAmount;
     System.out.println(Thread.currentThread().getName()+"开始取钱，余额为："+balance);
        cond.signalAll();
      }
   }catch (Exception e){
    e.printStackTrace();
   }finally {
     lock.unlock();
   }
  }
  //存钱
  public  void deposit(double depositAmount){
    lock.lock();
    try{
      //如果当前旗标为false，则说明账户没钱，不需要阻塞，开始存钱
      if(balance<0){
        cond.await();
      }else{
        balance+=depositAmount;
        System.out.println(Thread.currentThread().getName()+"开始存钱，余额为："+balance);
        //将表示账户是否已有存款的旗标为true
        cond.signalAll();
      }
    }catch (Exception e){
      e.printStackTrace();
    }finally {
      lock.unlock();
    }
  }
}
